package com.example.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.example.entity.LoginUser;
import com.example.utils.JwtUtil;
import com.example.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义验证token的过滤器，继承OncePerRequestFilter,保证过滤器会被执行一次
 * @author cjd
 * @date 2024/02/08 18:05
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 1、获取token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            // 放行（这里token为空，说明没有登录，放行之后，才会走到登录逻辑那里去。）
            filterChain.doFilter(request, response);
            return;
        }
        // 2、解析token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        // 3、从redis中获取用户信息
        String redisKey = "login:" + userId;
        Object userObject = redisCache.getCacheObject(redisKey);
        LoginUser loginUser = JSON.toJavaObject(JSON.parseObject(userObject.toString()), LoginUser.class);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        // 4、将用户信息存入SecurityContextHolder中
        // 获取权限信息封装到Authentication中，这里的第三个参数就是权限信息
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 5、放行，让请求进入controller
        filterChain.doFilter(request, response);
    }
}
